# coding: utf-8
# @Author: ChuiZi
import uuid

import pytest
import requests
from settings import switch


#  解决pytest用例编码名称乱码问题
def pytest_collection_modifyitems(items):
    for item in items:
        # 只需要对中括号内的数据做一个编码转换即可，防止因为测试用例本身就是中文导致编码再出问题
        names = item.name.split("[")
        nodeids = item.nodeid.split("[")
        if len(names) > 1:
            item.name = names[0] + "[" + names[-1].encode("utf-8").decode("unicode_escape")
        if len(nodeids) > 1:
            item._nodeid = nodeids[0] + "[" + nodeids[-1].encode("utf-8").decode("unicode_escape")


# 唯一id
@pytest.fixture(scope="function", autouse=True)
def one_id():
    oneid = str(uuid.uuid4()).replace("-", "")
    yield oneid


# 统一会话
@pytest.fixture(scope="session", autouse=True)
def one_session():
    one_session = None
    if switch["onesession"]:
        onesession = requests.session()
    yield onesession


# 全局变量,用来储存用例间的参数传递问题
global_data = {}


# 设置全局变量
@pytest.fixture(autouse=True)
def set_global_data():
    def _set_global_data(key, value):
        global_data[key] = value

    return _set_global_data


# 获取全局变量
@pytest.fixture(autouse=True)
def get_global_data():
    # 获取全局变量
    def _get_global_data(key):
        return global_data.get(key)

    return _get_global_data
